//初始化和扩展一些插件
(function($) {
	//图片上传
	$.handleUpload = function(el, options, callback) {}
    //end图片上传

    //表单提交
    $.handleForm = function(el, options, callback){
       var form = this;
        form.$el = $(el);

        var isForm = ($(el).prop('nodeName') == 'FORM');
        if(typeof options === 'function'){
            callback = options;
            options = {};
        }
        form.callback = null || callback;

        form.el = el;

        form.defaults = {
            rt : false,//实时验证,
            errorElement: 'div', //默认用于显示错误信息的标签 div span p
            errorClass: 'help-block', // 默认错误信息的样式
            focusInvalid: false, // 第一个错误的input获取焦点
            ignore: "", // 隐藏域,
            closest : '.form-group', //用于寻找parent的标识
            parentError: 'has-error',//parent高亮错误
            parentSuccess: 'has-success',//parent高亮成功
            ass: {//表单提交成功后的操作 none:不进行任何操作;reset:重置表单;alert:弹窗();closeWindow:关闭当前窗口;closeModal:关闭弹层;href:链接
                //'alert':'提交成功!'
                'none': true
            },
            pulsate: false,
            type: "POST", // 提交表单的方式,
            dataType: "JSON",//返回数据的格式
            beforeSubmit: null,
            confirm: null,
            isSubmit: null

        };

        form.options = $.extend({}, form.defaults, options);

        var $formSuccess = function (data, statusText, xhr, $form) {
            if (data) {
                $().cookie && $.cookie("refersh_time", 1);

                setTimeout(function(){
                    /* 提交成功后的常用操作 */
                    if(!form.options.ass.none){
                        form.options.ass.alert && bootbox.alert(form.options.ass.alert, function(){
                            form.options.ass.href && (document.location.href = form.options.ass.href);
                        });

                        form.options.ass.reset && $(form.el)[0].reset();

                        form.options.ass.closeWindow && window.close();

                        //form.options.ass.href && (form.options.ass.alert ? alert(form.options.ass.alert) : {}, (document.location.href = form.options.ass.href));
                        !form.options.ass.alert && (form.options.ass.href && (document.location.href = form.options.ass.href))
                    }
                    // console.log(form.callback);
                    form.callback && form.callback(data, statusText, xhr, $form);
                },1000);
            }
        }

        //表单验证开始
        //表单验证开始
        form.$el.validate({
            onclick : form.options.rt,//false,//实时验证
            errorElement: form.options.errorElement, //默认用于显示错误信息的标签 div span p
            errorClass: form.options.errorClass, // 默认错误信息的样式
            focusInvalid: form.options.focusInvalid, // 第一个错误的input获取焦点
            ignore: form.options.ignore, // 隐藏域
            rules: form.options.rules,

            messages: form.options.messages,

            errorPlacement: function (error, element) { // 处理错误信息
                el = $(element).prop('name');

                el.indexOf('[') == -1 && $('#'+ el +'-success').hide(); //先屏蔽成功信息
                /* if (element.prev("i.icon-check").size() > 0) {
                    var icon = element.prev("i.icon-check").prop('class').match(/fa\-\S+\b/g, '');
                    console.log(icon);
                    element.prev("i.icon-check").removeClass('fa-*').addClass('fa-times');
                } else  */

                // if (element.parent(".input-icon").size() > 0) {
                //     if($('#'+ el +'-error').length > 0)$('#'+ el +'-error').remove();//如果已存在错误信息,先删除
                //     error.insertAfter(element.parent(".input-icon"));
                // } else if (element.parent(".input-group").size() > 0) {
                //     error.insertAfter(element.parent(".input-group"));
                // } else if (element.attr("data-error-container")) {

                //     error.appendTo($('#'+element.attr("data-error-container")));
                // } else if (element.parents('.radio-list').size() > 0) {
                //     error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                // } else if (element.parents('.radio-inline').size() > 0) {
                //     error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                // } else if (element.parents('.checkbox-list').size() > 0) {
                //     error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                // } else if (element.parents('.checkbox-inline').size() > 0) {
                //     error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                // } else if (element.next('#'+error[0].id).size() > 0) {
                //     element.next('#'+error[0].id).replaceWith(error);
                // } else {
                //     //console.log($('#'+ el +'-error').length);
                //     //console.log(element);
                //     if(element.prop('type') != 'hidden'){
                //         if($('#'+ el +'-error').length > 0)$('#'+ el +'-error').remove();//如果已存在错误信息,先删除
                //     }
                //     error.insertAfter(element);
                // }
                if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                 var controls = element.closest('div[class*="col-"]');
                 if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                 else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
             }
             else if (element.is('.select2')) {
                 error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
             }
             else if (element.is('.chosen-select')) {
                 error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
             }
             else error.insertAfter(element.parent());
         },

         invalidHandler: function (event, validator) {
                //console.log(event, validator);
                if(typeof layer != 'undefined' && typeof validator.errorList[0].message == 'string'){
                    layer.msg(validator.errorList[0].message);
                }
                // Global.scrollTo($(validator.errorList[0].element));
                //console.log(validator.errorList);
            },

            highlight: function (element, label) { // 高亮错误
                // $(element).closest('.form-group').removeClass('has-info').addClass('has-error');
                el = $(element).prop('name');
                el.indexOf('[') == -1 && $('#'+ el +'-success', form.$el).hide();   //先屏蔽成功信息

                $(element).closest(form.options.closest).addClass(form.options.parentError);

                form.options.pulsate && $(element).pulsate({color: "#bf1c56", repeat: false});
            },

            unhighlight: function (element) { // 通过验证后移除高亮错误
                $(element).closest(form.options.closest).removeClass(form.options.parentError);
                var el = $(element).prop('name');
                el.indexOf('[') == -1 && $('#'+ el +'-error').remove();
            },

            success: function (label, element) {//通过验证后添加样式
                label.closest(form.options.closest).addClass(form.options.parentSuccess);
                var el = $(element).prop('name');
                el.indexOf('[') == -1 && $('#'+ el +'-error').remove();
                if(el.indexOf('[') == -1){
                    var elSuccess = $('#'+ el +'-success', form.$el);
                }else{
                    var elSuccess = {length:0};
                }
                if(elSuccess.length == 1){
                    elSuccess
                    .html(function(){
                        return (form.options.messages[el].success) ? '<i class="fa fa-check font-success"></i>' + form.options.messages[el].success : $(this).html();
                    })
                    .show();
                }else{
                    //console.log(form.options.messages[el]);

                    if(form.options.messages[el] && form.options.messages[el].success){
                        elSuccess = $('<span/>')
                        .prop('id', el +'-success')
                        .addClass('help-block')
                        .html('<i class="fa fa-check font-success"></i>' + form.options.messages[el].success);
                        $(element).after(elSuccess);
                    }
                }
            },

            submitHandler: function (subForm, e) {//验证通过,提交表单
                //e.preventDefault();

                if(form.options.confirm){
                    if(typeof form.options.confirm == 'string'){
                        var msg = form.options.confirm;
                    }else{
                        var msg = form.options.confirm();
                        msg = msg || '确定提交吗?';
                    }
                    bootbox.confirm(msg, function(res){
                        if(res){
                            submitForm(subForm, form, e);
                        }else{
                        };
                    });
                }else{
                    submitForm(subForm, form);
                }
            }

        });
        //表单验证结束

        var submitForm = function(subForm, form, e){
            // console.log(e);//
            if($("input[name='_ajax']", $(subForm)).length == 0){
                $(subForm).append('<input name="_ajax" type="hidden" value="1" />');
            }

            var sub = (typeof form.options.isSubmit === 'function') ? form.options.isSubmit() : form.options.isSubmit;
            if(sub){
                console.log(sub);
                subForm.submit();
                return false;
            }else{
                //console.log($formSuccess);
                try{
                    $(subForm).ajaxSubmit({
                        url : $(subForm).attr('action'),
                        type : form.options.type,
                        dataType : form.options.dataType,
                        beforeSubmit : function (arr, $form, options) {
                            if(form.options.beforeSubmit){
                                form.options.beforeSubmit();
                            }
                            if(typeof layer != 'undefined'){
                                // layer.load(3);
                            }else{
                                // Global.blockUI({zIndex: 99999});
                            }
                        },
                        success : $formSuccess
                    });
                }catch(e){
                    console.log(e);
                }
            }
        }
    };

    // editable
    // $.fn.editable.defaults.mode = 'inline';
    $.fn.editableform.loading = "<div class='editableform-loading'><i class='ace-icon fa fa-spinner fa-spin fa-2x light-blue'></i></div>";
    $.fn.editableform.buttons = '<button type="submit" class="btn btn-info editable-submit"><i class="ace-icon fa fa-check"></i></button>'+
    '<button type="button" class="btn editable-cancel"><i class="ace-icon fa fa-times"></i></button>';

    // end 表单提交
    $.fn.handleForm = function (options, callback) {
        return this.each(function (i) {
            (new $.handleForm(this, options, callback));
        });
    };

})(jQuery);

